package com.ponxu.mb.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ponxu.log.Log;
import com.ponxu.log.LogFactory;
import com.ponxu.web.core.WebContext;

/**
 * 权限
 * 
 * @author xwz
 * 
 */
public class AuthFilter implements Filter {
	private static final Log LOG = LogFactory.getLog();
	private static final String LOGIN = "/login";

	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		LOG.debug("----------AuthFilter begin----------");

		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;

		boolean processed = false;
		WebContext context = new WebContext(request, response);

		String uri = request.getServletPath();

		// 权限过滤
		if (uri.startsWith("/admin") && !isLogin(context)) {
			// 不可继续访问
			processed = true;
			context.redirect(LOGIN);
		}

		if (!processed) {
			chain.doFilter(request, response);
		}

		LOG.debug("----------AuthFilter end----------");
	}

	private boolean isLogin(WebContext context) {
		return context.sessionGet("admin") != null;
	}

	public void init(FilterConfig fConfig) throws ServletException {
	}

	public void destroy() {
	}
}
